package com.pig4cloud.pigx.common.security.service;

import cn.hutool.core.util.ArrayUtil;
import com.pig4cloud.pigx.common.security.constant.CommonConstants;
import com.pig4cloud.pigx.common.security.constant.SecurityConstants;
import com.pig4cloud.pigx.common.security.entity.SysUser;
import com.pig4cloud.pigx.common.security.entity.UserInfo;
import org.springframework.core.Ordered;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * @description:
 * @Author 兔子不吃窝边曹
 * @create 2022/7/15 15:05
 **/
public interface PigxUserDetailsService extends UserDetailsService, Ordered {


    /**
     * 构建userdetails
     *
     * @param userInfo 用户信息
     * @return UserDetails
     * @throws UsernameNotFoundException
     */
    default UserDetails getUserDetails(UserInfo userInfo) {
        if (Objects.isNull(userInfo)) {
            new UsernameNotFoundException("用户不存在");
        }
        return this.convertUserDetails(userInfo);
    }

    /**
     * UserInfo 转 UserDetails
     *
     * @param info
     * @return 返回UserDetails对象
     */
    default UserDetails convertUserDetails(UserInfo info) {
        Set<String> dbAuthsSet = new HashSet<>();
        if (ArrayUtil.isNotEmpty(info.getRoles())) {
            // 获取角色
            Arrays.stream(info.getRoles()).forEach(roleId -> dbAuthsSet.add(SecurityConstants.ROLE + roleId));
            // 获取资源
            dbAuthsSet.addAll(Arrays.asList(info.getPermissions()));

        }
        Collection<? extends GrantedAuthority> authorities = AuthorityUtils
                .createAuthorityList(dbAuthsSet.toArray(new String[0]));
        SysUser user = info.getSysUser();

        // 构造security用户
        return new PigxUser(user.getUserId(), user.getUsername(), user.getDeptId(), user.getPhone(), user.getAvatar(), user.getNickname(), user.getTenantId(),
                SecurityConstants.BCRYPT + user.getPassword(), true, true, true,
                !CommonConstants.STATUS_LOCK.equals(user.getLockFlag()), authorities);
    }

    /**
     * 根据mobile登录
     *
     * @param mobile
     * @return
     * @throws UsernameNotFoundException
     */
    UserDetails loadUserBySocial(String mobile) throws UsernameNotFoundException;
}
